package org.example.shop.service;

import org.example.shop.dao.UserDao;
import org.example.shop.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public UserInfo findByName(String name) {
        UserInfo u = new UserInfo().setUsername(name);
        Optional<UserInfo> info = userDao.findOne(Example.of(u));
        return info.isPresent() ? info.get() : null;
    }

    @Override
    public UserInfo save(UserInfo userInfo) {
        if (findByName(userInfo.getUsername()) != null) {
            throw new RuntimeException("用户名已经存在了");
        }
        return userDao.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username).setPassword(password);
        Optional<UserInfo> one = userDao.findOne(Example.of(userInfo));

        return one.isPresent() ? one.get() : null;
    }
}
